import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form, Input, Button, Modal, Select, Row, Col, InputNumber, message, Popconfirm } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data'
import { getDiscountList, addDiscountData, getMerNo, effect, delNotEffectByCustNo } from './service'
import TableTitle from '../../components/TableTitle'
// 生成折扣编码
import { getCode } from '@/services/generateCode';
import { history } from 'umi'

const { Option } = Select;
const { TextArea } = Input;

export default () => {
  // add模态框控制
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  // 添加用户数据表单验证 获取表单
  const [addFormRef] = Form.useForm();
  // 商户号保存
  const [merNo, setMerNo] = useState<string | undefined>(undefined)
  // 所有商户号
  const [allMerNo, setAllMerNo] = useState()
  // 新增表单数据储存
  const [response, setResponse] = useState()
  // 新增生效确认模态框
  const [isModalValidation, setIsModalValidation] = useState(false)

  React.useEffect(() => {
    // 当点击某一个商户的折扣配置进入页面时
    // 获取custNo 并赋值给merNo
    if (history.location.state?.custNo) {
      setMerNo(history.location.state?.custNo)
    }
    getAllMerNo()
  }, [])

  // 获取所有商户号
  const getAllMerNo = async () => {
    let data = await getMerNo({})
    console.log(data);

    setAllMerNo(data.body)
  }

  // 新增按钮
  const addInfo = async () => {
    setIsAddModalVisible(true);
    // 折扣编码 
    let disctNo = await getCode({ type: 0 })
    // 固定的数值
    let defaultData = {
      disctNo: disctNo.body.code,
      custNo: merNo,
      status: '0'
    }
    console.log('defaultData', defaultData);
    // 回显进入表单 用setState的话会出现组件被销毁但是state没有被销毁的事情
    addFormRef.setFieldsValue(defaultData);
  };

  // 新增表单确认按钮
  const handleAddOk = async () => {
    // 表单验证
    addFormRef.validateFields().then(async () => {
      // 获取新增表单的值
      var response = addFormRef.getFieldsValue();
      let { memRate, pltRate, recRate } = response
      let sum = memRate + pltRate + recRate
      console.log(sum);

      if (sum !== 100) {
        message.error('会员占比、平台占比、推荐人占比之和应为 100%')
        return
      }
      console.log('response', response);
      if (response.status === '0') {
        setIsModalValidation(true)
        setResponse(response)
        return
      }
      // 调用新增接口
      let data = await addDiscountData(response)
      console.log(data);
      if (data.sysHead.retCd === '000000') {
        message.success('配置未生效折扣规则成功')
      }
      // 重置表单
      addFormRef.resetFields();
      // 关闭模态框
      setIsAddModalVisible(false)
      // 表格重新渲染
      actionRef.current?.reload()
    }).catch(() => { })
  }

  // 新增确认模态框确认按钮
  const handleOkValidation = async () => {
    // 调用新增接口
    let data = await addDiscountData(response)
    console.log(data);
    if (data.sysHead.retCd === '000000') {
      message.success('配置生效折扣规则成功')
    }
    // 重置表单
    addFormRef.resetFields();
    // 关闭模态框
    setIsModalValidation(false)
    setIsAddModalVisible(false)
    // 表格重新渲染
    actionRef.current?.reload()
  }

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData

  // 定义操作单元格
  const columnsRender = (text: any, record: columnsDataType) => {
    if (record.status === '2') {
      return [
        <ul className="ant-list-item-action" key='option' style={{ margin: 0 }}>
          <li>
            <Popconfirm
              title="是否生效本条配置？"
              okText="是"
              cancelText="否"
              onConfirm={async () => {
                let data = await effect({ custNo: record.custNo })
                if (data.sysHead.retCd === '000000') {
                  message.success('生效折扣规则成功')
                }
                // 表格重新渲染
                actionRef.current?.reload()
              }}
            >
              <a>
                生效
              </a>
            </Popconfirm>
            <em className="ant-list-item-action-split"></em>
          </li>
          <li>
            <Popconfirm
              title="是否删除本条配置？"
              okText="是"
              cancelText="否"
              onConfirm={async () => {
                let data = await delNotEffectByCustNo({ custNo: record.custNo })
                console.log(data);
                if (data.sysHead.retCd === '000000') {
                  message.success('删除未生效折扣规则成功')
                  // 表格重新渲染
                  actionRef.current?.reload()
                }
              }}
            >
              <a>
                删除
              </a>
            </Popconfirm>
          </li>
        </ul>
      ]
    }
  }

  // 定义金额单元格
  const amountRender = (text: any) => [
    <p
      key='amount'
      style={{ textAlign: 'right', margin: 0 }}
    >
      {typeof text === 'number' ? text.toFixed(6) : null}
    </p>
  ]

  // 列渲染样式赋值
  columns.forEach(item => {
    item.dataIndex === 'disctMinLmt' ? item.render = amountRender : undefined
    item.valueType === 'option' ? item.render = columnsRender : undefined
  })

  // Table action 的引用，便于自定义触发，为了下面的reload
  const actionRef = React.useRef<ActionType>();
  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<div style={{ display: 'flex', alignItems: 'center' }}>
          <TableTitle title='折扣查询' />
        </div>}
        actionRef={actionRef}
        scroll={{ x: 900 }}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={
          async params => {
            if (merNo && !params.merNo) {
              params.merNo = merNo
            }
            console.log(params);

            let res = await getDiscountList({ ...params, pageNum: params.current })
            console.log('discount@@@@', res);
            if (res) {
              const result = {
                data: res.body.list,
                total: res.body.total,
              }
              return result
            }
            return {
              data: [],
              total: 0,
            }
          }
        }
        rowKey="disctNo"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        //设置工具栏按钮及事件
        toolBarRender={() => [
          <div>
            <Button key="add" icon={<PlusOutlined />} type="primary" onClick={addInfo}>
              新增
            </Button>
          </div>
        ]}
      />
      {/* 新增模态框 */}
      <Modal
        title="折扣新增"
        centered
        visible={isAddModalVisible}
        onOk={handleAddOk}
        onCancel={() => setIsAddModalVisible(false)}
        okText="提交"
        width={700}
        forceRender={true}
      >
        <Form
          name="basic"
          form={addFormRef}
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          initialValues={{ state: 'effect' }}
          autoComplete="off"
        >
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="折扣所属商户"
                name="custNo"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  }
                ]}
              ><Select
                showSearch
                placeholder="请选择商户"
                optionFilterProp="children"
                filterOption={(input, option) => {
                  return option?.name?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                }
              >
                  {
                    allMerNo ?
                      allMerNo.map((item: any) =>
                        <Option key={item.custNo} value={item.custNo} name={item.custName}>{item.custName}</Option>) :
                      null
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="折扣编码"
                name="disctNo"
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="生效状态"
                name="status"
              >
                <Select>
                  <Option value='0'>生效</Option>
                  <Option value='2'>未生效</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="折扣名称"
                name="disctNm"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  }
                ]}
              >
                <Input maxLength={20} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="折扣抵消(CAD)"
                name="disctMinLmt"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  }
                ]}
              >
                <InputNumber maxLength={20} style={{ width: '100%' }} precision={2} min={0} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="折扣总比例(%)"
                name="disctRate"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  },
                ]}
              >
                <InputNumber maxLength={20} style={{ width: '100%' }} step={1} precision={0} max={99} min={1} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="会员占比(%)"
                name="memRate"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  },
                ]}
              >
                <InputNumber maxLength={20} style={{ width: '100%' }} step={1} precision={0} max={100} min={1} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="平台占比(%)"
                name="pltRate"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  },
                ]}
              >
                <InputNumber maxLength={20} style={{ width: '100%' }} step={1} precision={0} max={100} min={1} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="推荐人占比(%)"
                name="recRate"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  },
                ]}
              >
                <InputNumber maxLength={20} style={{ width: '100%' }} step={1} precision={0} max={100} min={1} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={24}>
              <Form.Item
                label="备注"
                name="rmk"
              >
                <TextArea maxLength={225} rows={4} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      {/* 新增生效确认 */}
      <Modal
        visible={isModalValidation}
        onOk={handleOkValidation}
        onCancel={() => {
          setIsModalValidation(false)
        }}
        centered
      >
        <div
          style={{
            height: 60,
            lineHeight: '60px',
            textAlign: 'center',
            fontSize: 30,
            fontWeight: 500
          }}>
          确认生效当前折扣配置
        </div>
      </Modal>
    </div>
  );
};